import type { Router, LocationQueryRaw } from 'vue-router';
import NProgress from 'nprogress'; // progress bar

import { useUserStore } from '@/store';
import { isLogin } from '@/utils/auth';
import { DEFAULT_HOME } from '@/router/constants';

export default function setupUserLoginInfoGuard(router: Router) {
    router.beforeEach(async (to, from, next) => {
        NProgress.start();
        const userStore = useUserStore();
        if (isLogin()) {
            if (to.name === 'login') {
                const defaultHome = userStore.firstMenuItem?.component
                    ? { name: userStore.firstMenuItem?.component }
                    : DEFAULT_HOME;
                next(defaultHome);
                return;
            }
            if (userStore.menuList?.length) {
                next();
            } else {
                try {
                    await userStore.info();
                    next();
                } catch (error) {
                    await userStore.logout();
                    next({
                        name: 'login',
                        query: {
                            redirect: to.name,
                            ...to.query,
                        } as LocationQueryRaw,
                    });
                }
            }
        } else {
            if (to.name === 'login') {
                next();
                return;
            }
            next({
                name: 'login',
                query: {
                    redirect: to.name,
                    ...to.query,
                } as LocationQueryRaw,
            });
        }
        NProgress.done();
    });
}
